package net.xdclass.controller;


import com.alibaba.fastjson.JSON;
import com.alipay.api.AlipayApiException;
import com.alipay.api.request.AlipayTradeAppPayRequest;
import com.alipay.api.request.AlipayTradePayRequest;
import com.alipay.api.request.AlipayTradeWapPayRequest;
import com.alipay.api.response.AlipayTradeAppPayResponse;
import com.alipay.api.response.AlipayTradeWapPayResponse;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import jodd.util.StringUtil;
import lombok.extern.slf4j.Slf4j;
import net.xdclass.config.AlipayConfig;
import net.xdclass.config.PayUrlConfig;
import net.xdclass.constant.CacheKey;
import net.xdclass.enums.*;
import net.xdclass.exception.BizException;
import net.xdclass.interceptor.LoginInterceptor;
import net.xdclass.model.LoginUser;
import net.xdclass.request.ConfirmOrderRequest;
import net.xdclass.request.RepayOrderRequest;
import net.xdclass.service.ProductOrderService;
import net.xdclass.utils.CommonUtils;
import net.xdclass.utils.JsonData;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.script.DefaultRedisScript;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Arrays;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;
import java.util.concurrent.TimeUnit;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author 二当家小D
 * @since 2021-12-31
 */
@Api("訂單模块")
@RestController
@RequestMapping("/api/order/v1")
@Slf4j
public class ProductOrderController {

    @Autowired
    private ProductOrderService orderService;

    @Autowired
    private PayUrlConfig payUrlConfig;

    @Autowired
    private RedisTemplate redisTemplate;

    @ApiOperation("獲取提交訂單令牌")
    @GetMapping("get_token")
    public JsonData getOrderToken() {
        LoginUser loginUser = (LoginUser) LoginInterceptor.threadLocal.get();
        String key =String.format(CacheKey.SUBMIT_ORDER_TOKEN_KEY, loginUser.getId());
        String token = CommonUtils.getStringNumRandom(32);
        redisTemplate.opsForValue().set(key, token, 30, TimeUnit.MINUTES);

        return JsonData.buildSuccess(token);
    }

    @ApiOperation("分頁查詢我的訂單列表")
    @GetMapping("page")
    public JsonData pageProductList(
            @ApiParam(value = "當前頁") @RequestParam(value = "page", defaultValue = "1") int page,
            @ApiParam(value = "每頁顯示多少條") @RequestParam(value = "size", defaultValue = "10") int size,
            @ApiParam(value = "訂單狀態") @RequestParam(value = "state", required = false) String state
    ) {
        Map<String, Object> pageResult = orderService.page(page, size, state);

        return JsonData.buildSuccess(pageResult);
    }

    @ApiOperation("确認訂單")
    @PostMapping("confirm")
    public void confirmOrder(@ApiParam("訂單對象") @RequestBody ConfirmOrderRequest orderRequest,
                             HttpServletResponse response
    ) {
        JsonData jsonData = orderService.confirmOrder(orderRequest);

        if (jsonData.getCode() == 0) {
            String client = orderRequest.getClientType();
            String payType = orderRequest.getPayType();

            if (payType.equalsIgnoreCase(ProductOrderPayTypeEnum.ALIPAY.name())) {
                log.info("創建支付寶訂單成功 {}", orderRequest.toString());
                if (client.equalsIgnoreCase(ClientType.H5.name())) {
                    writeData(response, jsonData);
                }
            }
        } else {
            log.error("創建訂單失敗", jsonData.toString());
            CommonUtils.sendJsonMessage(response, jsonData);
        }
    }

    @ApiOperation("确認訂單")
    @PostMapping("repay")
    public void repay(@ApiParam("訂單對象") @RequestBody RepayOrderRequest repayOrderRequest,
                             HttpServletResponse response
    ) {
        JsonData jsonData = orderService.repay(repayOrderRequest);

        if (jsonData.getCode() == 0) {
            String client = repayOrderRequest.getClientType();
            String payType = repayOrderRequest.getPayType();

            if (payType.equalsIgnoreCase(ProductOrderPayTypeEnum.ALIPAY.name())) {
                log.info("重新創建支付寶訂單成功 {}", repayOrderRequest.toString());
                if (client.equalsIgnoreCase(ClientType.H5.name())) {
                    writeData(response, jsonData);
                }
            }
        } else {
            log.error("重新創建訂單失敗", jsonData.toString());
            CommonUtils.sendJsonMessage(response, jsonData);
        }
    }

    private void writeData(HttpServletResponse response, JsonData jsonData) {
        try {
            response.setContentType("text/html;charset=UTF-8");
            response.getWriter().write(jsonData.toString());
            response.getWriter().flush();
            response.getWriter().close();
        } catch (IOException e) {
            log.error("寫出html異常 {}", e);
        }
    }

    @ApiOperation("查詢訂單狀態")
    @GetMapping("query_state")
    public JsonData queryProductOrderState(@ApiParam("訂單號") @RequestParam("out_trade_no") String outTradeNo) {
        String state = orderService.queryProductOrderState(outTradeNo);

        return StringUtils.isBlank(state) ? JsonData.buildResult(BizCodeEnum.ORDER_CONFIRM_NOT_EXIST) :
                JsonData.buildSuccess();
    }

    @GetMapping("test_pay")
    public void testAlipay(HttpServletResponse response) throws AlipayApiException, IOException {
        Map<String, String> content = new HashMap<>();
        //商户订单号,64个字符以内、可包含字母、数字、下划线；需保证在商户端不重复
        String no = UUID.randomUUID().toString();
        log.info("订单号:{}",no);
        content.put("out_trade_no", no);
        content.put("product_code", "FAST_INSTANT_TRADE_PAY");
        //订单总金额，单位为元，精确到小数点后两位
        content.put("total_amount", String.valueOf("111.99"));
        //商品标题/交易标题/订单标题/订单关键字等。 注意：不可使用特殊字符，如 /，=，&amp; 等。
        content.put("subject", "杯子");
        //商品描述，可空
        content.put("body", "好的杯子");
        // 该笔订单允许的最晚付款时间，逾期将关闭交易。取值范围：1m～15d。m-分钟，h-小时，d-天，1c-当天（1c-当天的情况下，无论交易何时创建，都在0点关闭）。 该参数数值不接受小数点， 如 1.5h，可转换为 90m。
        content.put("timeout_express", "5m");

        AlipayTradeWapPayRequest request = new AlipayTradeWapPayRequest();
        request.setBizContent(JSON.toJSONString(content));
        request.setNotifyUrl(payUrlConfig.getAlipayCallbackUrl());
        request.setReturnUrl(payUrlConfig.getAlipaySuccessReturnUrl());

        AlipayTradeWapPayResponse alipayTradePayReponse = AlipayConfig.getInstance().pageExecute(request);
        if (alipayTradePayReponse.isSuccess()) {
            log.info("調用成功");
            String form = alipayTradePayReponse.getBody();
            response.setContentType("text/html;charset=UTF-8");
            response.getWriter().write(form);
        } else {
            log.error("調用失敗");
        }
    }


}

